package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 自动审核功能实现
     *
     * @param wmNewsId 自媒体文章id
     */
    @Override
    public void autoScanWmNews(Integer wmNewsId) {
        log.info("自动审核方法被调用,当前审核的文章id为:{}", wmNewsId);
        //数据检查
        if (wmNewsId == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请传入正确的文章id");
        }
        //根据id查询文章内容
        WmNews wmNews = wmNewsMapper.selectById(wmNewsId);
        //判断文章内容是否存在
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询不到文章信息");
        }
        //先判断文章是否为待审核状态
        Short status = wmNews.getStatus();
        if (status.equals(WmNews.Status.SUBMIT.getCode())) {
            //将文章中的图片路径和文章内容全部变为集合的形式
            Map<String, Object> contentAndImageResult = handleTextAndImages(wmNews);
            //敏感词审核
            boolean isSensitive = handleSensitive((String) contentAndImageResult.get("content"), wmNews);
            //判断是否存在敏感词若是存在直接停止方法
            if (isSensitive) return;
            log.info(" 自管理敏感词审核通过  =======   ");
            //阿里云文本审核
            boolean isText = handleTextScan((String) contentAndImageResult.get("content"), wmNews);
            //审核未通过直接停止方法
            if(!isText)return;
            log.info(" 阿里云内容审核通过  =======   ");
            //阿里云图片审核  先判断文章中是否有图片信息
            Object images = contentAndImageResult.get("images");
            if(images!=null){
                //阿里云审核
               boolean isImages =  handleImageScan((List<String>) images, wmNews);
                //审核未通过直接停止方法
                if(!isImages) return;
                log.info(" 阿里云图片审核通过  =======   ");
            }
        }
        //判断文章发布时间是否大于当前时间
        updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(),"审核成功");

        // 发送消息到延时 队列
        //获取创建时间
        long publishTime = wmNews.getPublishTime().getTime();
        //获取当前时间
        long xianzaiTime = new Date().getTime();
        //现在 - 创建 == 发布
        long remainTime = publishTime - xianzaiTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

    }
    @Autowired
    GreenImageScan greenImageScan;

    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        //
        try {
            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "审核未通过,图片中有违规信息");
                    flag = false;
                    break;
                case "review":
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"图片中有不确定信息,转至人工审核");
                    flag=false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云图片审核出现异常 , 原因:{}",e.getMessage());
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云服务器出现异常,转至人工审核");
        }
        return flag;

    }

    @Autowired
    GreenTextScan greenTextScan;

    /**
     * 阿里云文本审核
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        //
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "审核未通过,文章中有违规信息");
                    flag = false;
                    break;
                case "review":
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"文章中有不确定信息,转至人工审核");
                    flag=false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核出现异常 , 原因:{}",e.getMessage());
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云服务器出现异常,转至人工审核");
        }
        return flag;
    }

    @Autowired
    private AdminFeign adminFeign;

    /**
     * 文章敏感词审核方法实现
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = false;
        //查询数据库中的所有敏感词
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        //判断是否保存了敏感词
        if (sensitives.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, sensitives.getErrorMessage());
        }
        List<String> sensitivesData = sensitives.getData();
        //将敏感词集合转发DFA数据模型
        SensitiveWordUtil.initMap(sensitivesData);
        //
        Map<String, Integer> matchWords = SensitiveWordUtil.matchWords(content);
        if (matchWords != null && matchWords.size() > 0) {
            flag = true;
            //修改文章状态
            updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "内容中包含敏感词: " + matchWords);
        }
        return flag;
    }

    /**
     * 修改文章状态
     *
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 将文本和图片转为集合
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //
        String contentJson = wmNews.getContent();
        //数据检查
        if (contentJson == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //将文章内容(json数组)转换为集合
        List<Map> contentMaps = JSONArray.parseArray(contentJson, Map.class);
        //过滤所有 text文本类
        String content = contentMaps.stream().filter(m -> "text".equals(m.get("type")))
                //获取所有文本信息
                .map(m -> (String) m.get("value"))
                //终止操作 中间以_hmtt_分割
                .collect(Collectors.joining("_hmtt_"));
        //将标题也添加到文本中
        content = content + "_hmtt_" + wmNews.getTitle();
        //获取所有图片路径
        List<String> images = contentMaps.stream().filter(m -> "image".equals(m.get("type")))
                //获取所有图片路径
                .map(m -> (String) m.get("value"))
                //转为集合
                .collect(Collectors.toList());
        //如果有图片的话 数据库中存储的不是全路径 需要拼接
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            List<String> urls = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            images.addAll(urls);
        }
        // 3. 去重
        images = images.stream().distinct().collect(Collectors.toList());

        Map result = new HashMap();

        result.put("content", content);
        result.put("images", images);
        return result;

    }
}
